package com.example.kfcclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

	private EditText txtUsername;
	private EditText txtPassword;
	private TextView txtError;
	private Button btnLogin;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        

        // Khai báo các nút 
        txtUsername = (EditText) findViewById(R.id.username);
        txtPassword = (EditText) findViewById(R.id.password);
        txtError = (TextView) findViewById(R.id.error_login);
        btnLogin = (Button) findViewById(R.id.btn_login);
        ///////////////////////////////////////
        
        btnLogin.setOnClickListener(this);   // xét sự kiện onclick cho nút  
    }

    // sự kiện onclick 
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// kiểm tra có kết nối internet hay không ?
		if(CheckNetwork() == false)
		{
			Toast.makeText(Login.this, "Error connect internet", Toast.LENGTH_LONG).show();
		}
		else
		{
			postLoginData();
		}
	}
	
	// lấy dữ liệu từ server về
	public void postLoginData()
	{
		try{
			
			String url = "http://khoaluankfc.freevnn.com/API/login.php";
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			
			String username = txtUsername.getText().toString();
			String password = txtPassword.getText().toString();
			nameValuePairs.add(new BasicNameValuePair("username",username));
			nameValuePairs.add(new BasicNameValuePair("password", password));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			long t = System.currentTimeMillis();
			HttpResponse httpResponse = httpClient.execute(httpPost);
			Log.i("http client", "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
			HttpEntity httpEntity = httpResponse.getEntity();
			if(httpEntity != null)
			{
				InputStream in = httpResponse.getEntity().getContent();
				String result = convertStreamToString(in);
				Log.i("read from server", result);
				JSONObject json = new JSONObject(result);
				int number = json.getInt("number_table");
				if(json.getInt("success")==1)
				{
					Intent intent = new Intent(Login.this,ListFood.class);
					intent.putExtra("table", number);
					startActivity(intent);
				}
				else
				{
					txtError.setText("incorrect password or username");
				}
				
			}
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	// hàm chuyển dữ liệu từ server về dạng chuỗi
	private static String convertStreamToString(InputStream is) {

	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();

	    String line = null;
	    try {
	        while ((line = reader.readLine()) != null) {
	            sb.append(line + "\n");
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        try {
	            is.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	    return sb.toString();
	}
	
	//hàm kiểm tra kết nối mạng
	public boolean CheckNetwork()
	{
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if(networkInfo != null && networkInfo.isConnected())
		{
			return true;
		}
			return false;
		
	}
}
  